﻿using UnityEngine;
using Baidu.Aip.BodyAnalysis;
using Newtonsoft.Json.Linq;
using System.IO;
using System;

public class BaiduFaceAI : SingletonMono<BaiduFaceAI>
{
    // 设置APPID/AK/SK
    const string APP_ID = "17232432";
    const string API_KEY = "5iTKlCeRgBkFnCcKi7yLGLGd";
    const string SECRET_KEY = "U6ogpjId1OOWDnCRrAjSSEdSFvs1ZEhv";

    private Body client;

    void Start()
    {
        client = new Body(API_KEY, SECRET_KEY);
        client.Timeout = 60000;  // 修改超时时间
    }

    /// <summary>
    /// 检测图像byte流
    /// </summary>
    /// <param name="image">图像或者摄像的byte流</param>
    /// <param name="callback">回调是否是人体</param>
    public void BodyAnalysis(byte[] image,Action<bool> callback)
    {
        try
        {
            //加载本地图片
            //string path = Application.dataPath + "/test.jpg";
            //var image = File.ReadAllBytes(path);

            //接受图像的bytes
            var result = client.BodyAnalysis(image);
            callback(IsHuman(result));
        }
        catch (System.Exception e)
        {
            Debug.Log(e);
        }
    }

    /// <summary>
    /// //过滤方法：当关键点得分大于0.2的个数大于3，且人体框的分数大于0.03时，才认为是有效人体
    /// </summary>
    /// <param name="result">检测的JObject结果</param>
    /// <returns>是否是人体</returns>
    bool IsHuman(JObject result)
    {
        var persons = result["person_info"].Children();
        //多个人
        foreach (var person in persons)
        {
            //单个人的身体部位
            var parts = person["body_parts"].Children();
            var bodyScore = float.Parse(person["location"]["score"].ToString());

            if (bodyScore > 0.03f)
            {
                int count = 0;
                foreach (var part in parts)
                {
                    var keys = part.Children();
                    foreach (var item in keys)
                    {
                        if (float.Parse(item["score"].ToString()) > 0.2f)
                        {
                            count++;
                        }
                    }
                    if (count > 3)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
